<template>
    <ElDialog
        ref="dialog"
        custom-class="modal-import"
        v-model="importModal"
        :close-on-click-modal="false"
        :title='`批量导入${mainName}信息`'
        width="35%"
        :open-delay="100"
    >
        <div v-if="!isInstitution">
            <div class="import-progress" v-if="importResult.status === 1">
                <div class="ip-tip">正在上传，请稍后…</div>
                <el-progress :percentage="percent" :color="['#5C80ED', '#1890FF']" :stroke-width="6"/>
            </div>
            <div class="import-result" v-else-if="importResult.status === 0 || importResult.status === 2 || importResult.status === 3">
                <div class="ir-title">
                    <div class="irt-key">本次将要导入的数据共计：</div>
                    <div class="irt-value">{{ importResult.totalNum }}</div>
                </div>
                <div :class="['ir-content', !!importResult.dataFormatNotRightNum && 'ir-content-warn' || '']">
                    <div :class="['irc-key']">
                        <i v-if="!!importResult.dataFormatNotRightNum" class="iconfont icon-warn"></i>
                        用户信息格式不正确：
                    </div>
                    <div class="irc-value">{{ importResult.dataFormatNotRightNum }}</div>
                </div>
                <div :class="['ir-content', !!importResult.memberInfoNotCompleteNum && 'ir-content-warn' || '']">
                    <div :class="['irc-key']">
                        <i v-if="!!importResult.memberInfoNotCompleteNum" class="iconfont icon-warn"></i>
                        用户信息不完整：
                    </div>
                    <div class="irc-value">{{ importResult.memberInfoNotCompleteNum }}</div>
                </div>
                <div class="ir-content">
                    <div class="irc-key">变更用户：</div>
                    <div class="irc-value">{{ importResult.updateNum }}</div>
                </div>
                <div class="ir-content">
                    <div class="irc-key">新增用户：</div>
                    <div class="irc-value">{{ importResult.addNum }}</div>
                </div>
            </div>
            <div class="upload-file" v-else-if="!isInstitution">
                <upload-oss
                    :uploadSuccess="uploadSuccess"
                    :uploadFail="uploadFail"
                >
                    <div class="upload-oss-main">
                        <div class="main-key">文件：</div>
                        <div class="main-file" v-if="file && file.name">
                            <div class="file-name">{{ file.name }} </div>
                            <i class="iconfont iconruxiaofuwu_danchuangguanbi" @click.stop="reset"></i> 
                        </div>
                        <el-button  class="bd-m-file" ref="fileToUp" ><i class="iconfont  icon-download-file"></i>{{ file && file.name ? '更换文件' : '选择文件'}}</el-button>
                        <div class="main-tip">支持 xls，xlsx 文件格式</div>    
                    </div>
                </upload-oss>  
                <div class="down-modal">
                    如果没有模板请
                    <a 
                        class="down-modal-a" 
                        :href="handleHref"
                    >下载{{isInstitution ? '组织' : '教师'}}导入模版</a>
                </div>
            </div>
        </div>
        <div v-else>
            <div class="import-progress" v-if="importResult.status === 1">
                <div class="ip-tip">正在上传，请稍后…</div>
                <el-progress :percentage="percent" :color="['#5C80ED', '#1890FF']" :stroke-width="6"/>
            </div>
            <div v-else-if="importResult.status === 2">
                <div class="ip-tip">导入成功</div>
            </div>
            <div v-else-if="importResult.status === 3">
                <div class="ip-tip">部分导入失败</div>
            </div>
            <div class="upload-file" v-else>
                <upload-oss
                    :uploadSuccess="uploadSuccess"
                    :uploadFail="uploadFail"
                >
                    <div class="upload-oss-main">
                        <div class="main-key">文件：</div>
                        <div class="main-file" v-if="file && file.name">
                            <div class="file-name">{{ file.name }} </div>
                            <i class="iconfont iconruxiaofuwu_danchuangguanbi" @click.stop="reset"></i> 
                        </div>
                        <el-button  class="bd-m-file" ref="fileToUp" ><i class="iconfont  icon-download-file"></i>{{ file && file.name ? '更换文件' : '选择文件'}}</el-button>
                        <div class="main-tip">支持 xls，xlsx 文件格式</div>    
                    </div>
                </upload-oss>  
                <div class="down-modal">
                    如果没有模板请
                    <a 
                        class="down-modal-a" 
                        :href="handleHref"
                    >下载{{isInstitution ? '组织' : '教师'}}导入模版</a>
                </div>
            </div>

        </div>
        <template #footer>
            <div class="modal-footer">
                <el-button 
                    v-if="importResult.status != 2 && importResult.status != 3"
                    @click="cancel" 
                    :disabled="importResult.status === 1"
                >{{importResult.status === 0 && '取消导入' || '取消'}}</el-button>
                <template v-if="importResult.status !== 1">
                    <template v-if="importResult.status === 0">
                        <el-button 
                            type="primary"
                            v-if="!importResult.memberInfoNotCompleteNum && !importResult.dataFormatNotRightNum"
                            @click="importTeacherAccount(true)" 
                            :class="['modal-ok-btn', !uploadUrl && 'modal-ok-btn-disable' || '']"
                        >提交</el-button> 
                        <el-button 
                            type="primary"
                            v-else
                            @click="reset" 
                            :class="['modal-ok-btn', !uploadUrl && 'modal-ok-btn-disable' || '']"
                        >重新导入</el-button> 
                    </template>
                    <el-button 
                        type="primary"
                        v-else-if="importResult.status === 2 || importResult.status === 3"
                        @click="cancel" 
                        :class="['modal-ok-btn', !uploadUrl && 'modal-ok-btn-disable' || '']"
                    >确定</el-button>
                    <el-button 
                        type="primary"
                        v-else-if="!!uploadUrl"
                        @click="importTeacherAccount(false)" 
                        :class="['modal-ok-btn', !uploadUrl && 'modal-ok-btn-disable' || '']"
                    >确定导入</el-button>
                </template>
            </div> 
        </template>  
    </ElDialog>
</template>

<script>
import { defineComponent, watch, reactive, toRefs, onUnmounted, computed, ref} from 'vue';
import UploadOss from '@/components/upload/upload-oss-file.vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
export default defineComponent({
    props: ['parentInstitutionId', 'isInstitution'],
    emits: ['on-refresh'],
    components: {
        UploadOss
    },
    setup(props, ctx){
        const store = useStore()
        const route = useRoute()
        const fileToUpRef = ref(null)
        const state = reactive({
            isUpload: false,
            percent: 0,
            importModal: false,
            file: {},
            uploadUrl: '',
            importResultId: '',
            importResult: {},
            interval: null
        })
        const methods = {
            open() {
                methods.reset();
                state.importModal = true;
            },
            download() {},
            clear() {
                state.percent = 0;
                state.interval && clearInterval(state.interval);
                state.interval = null;
            },
            reset() {
                state.file = null;
                state.uploadUrl = '';
                state.importResultId = '';
                state.importResult = {};
            },
            uploadSuccess(url, file) {
                state.file = file;
                state.uploadUrl = url;
            },
            uploadFail() {
                store.dispatch('message', {
                    message: '上传失败'
                });
            },
            selectFile() {
                let input = fileToUpRef.value;
                input.value = '';
            },
            getFile(event) {
                state.file = event.target.files[0];
            },
            cancel() {
                methods.reset();
                state.importModal = false;
                ctx.emit('on-refresh')
            },
            // 获取导入结果
            getImportVO(booleanImportAccount) {
              console.log(booleanImportAccount, '1231323')
                store.dispatch('proxyAction', {
                    name: 'getImportVO',
                    message: false,
                    queries: {
                        importResultId: state.importResultId || ''
                    }
                }).then((res) => {
                    // if(res.success){
                        state.importResult = res.data || {};
                        state.isUpload = state.importResult.status === 1;
                        state.percent < 90 && (state.percent += 10);
                        if(booleanImportAccount) {
                            if(state.importResult.status === 2) {
                                store.dispatch('message', {
                                    message: '导入成功'
                                });
                                state.importResultId = false;
                                methods.cancel();
                                methods.clear();
                            } 
                            if(state.importResult.status === 3) {
                                // state.$Message.error('导入失败'); 
                                store.dispatch('message', {
                                    message: '导入失败'
                                });
                                methods.clear();
                            }
                        } else {
                            if(state.importResult.status !== 1) {
                                methods.clear();
                            }    
                        }
                    // } else {
                    //     methods.clear();
                    // }
                }).catch(err => {
                    console.log(err)
                    methods.clear();
                })
            },
            // 上传文件
            importTeacherAccount(booleanImportAccount) {
                if(!state.uploadUrl) {
                    store.dispatch('message', {
                        message: '请选择文件后上传'
                    });
                    return;
                }
                store.dispatch('proxyAction', {
                    name: props.isInstitution ? 'importInstitutionImport' : 'importTeacherAccount', // 'projectUserImport',
                    message: false,
                    data: {
                        booleanImportAccount: !!booleanImportAccount,
                        fileName: state.file && state.file.name || '',
                        importResultId: state.importResultId || '',
                        institutionId: route.query.id || undefined,
                        uploadUrl: state.uploadUrl || '',
                        version: props.isInstitution ? 'v2' : undefined
                    }
                }).then((res) => {
                    // if(res.success){
                        if(booleanImportAccount) {
                            state.isUpload = true;
                            state.importResult.status = 1
                        }
                        state.importResultId = res.data && res.data.importResultId;
                        methods.getImportVO(booleanImportAccount);
                        !state.interval ? (state.interval = setInterval(() => {
                            methods.getImportVO(booleanImportAccount);
                        }, 2000)) : (methods.clear()); 
                        
                    // }else{
                    //     console.log(res,'res')
                    //     // state.$Message.error(res.message || '导入失败');
                    //     store.dispatch('message', {
                    //         message: res.message || '导入失败'
                    //     });
                    //     methods.clear();
                    // }
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '导入失败'
                    });
                    methods.clear();
                });
            }
        }
        const comp = {
            handleHref: computed(() => {
                return props.isInstitution 
                  ? 'https://srt-read-online.3ren.cn/basebusiness/material/20220428/1651128176130uVRvCswo5m001.xlsx' 
                  : 'https://srt-read-dev.3ren.cn/basebusiness/institutionschool/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'

            }),
            mainName: computed(() => props.isInstitution ? '组织' : '用户')
        }
        onUnmounted(() => {
            methods.clear();
        })
        return {
            ...methods,
            ...toRefs(state),
            ...comp,
            fileToUpRef
        }
    }
})
</script>

<style lang="scss" scoped>
.modal-import {
    text-align: center;
    .modal-cancel-btn {
        display: inline-block;
        width: 65px;
        height: 35px;
        background: #FFFFFF;
        border-radius: 2px;
        border: 1px solid #D9D9D9;
        color: #666;
        cursor: pointer;
        text-align: center;
        // line-height: 34px;
        margin-right: 10px;
        &.modal-cancel-btn-disable {
            opacity: 0.6;
            cursor: not-allowed;
        }
    }
    .modal-ok-btn {
        // @include primary-btn();
        &.modal-ok-btn-disable {
            opacity: 0.6;
            cursor: not-allowed;
        }
    }
    .ip-tip {
        font-size: 18px;
        color: #666;
        margin-bottom: 40px;
    }
    .ir-title, .ir-content {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .irt-key, .irt-value {
        font-size: 18px;
        color: #000000; 
        &.irt-value {
            font-weight: bold;
        }
    }
    .ir-title {
        font-size: 18px;
        color: #000000;
        line-height: 24px;
        padding: 10px 30px 20px;
        border-bottom: 1px solid #F1F1F1;
    }
    .ir-content {
        font-size: 16px;
        color: #666;
        margin-top: 15px;
    }
    .ir-content-warn {
        color: #BC3030 !important;
    }
    .irc-value {
        color: #000;
        font-size: 24px;
        font-weight: bold;
    }
    .irt-value {
        font-weight: bold;
    }
    // /deep/ {
    //     .ivu-modal-body {
    //         padding: 20px 30px;
    //     }
    // }
}
.icon-download-file:before{
    margin-right: 10px;
}
.main-content {
    display: flex;
    justify-content: center;
}
.bd-m-file {
    color: #2D8cF0;
    border-color:  #2D8cF0;
    border-radius: 4px;
    margin-right:  10px;
    cursor: pointer;
}
.iconruxiaofuwu_shangchuanwenjian {
    padding-right: 10px;
}
.main-key {
    color: #666666;
}
.upload-oss-main {
    display: flex;
    align-items: center;
}
.main-file {
    width: 230px;
    height: 38px;
    background: #F5F5F5;
    border-radius: 2px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    margin-right: 20px;
}
.file-name {
    width: 185px;
    color: #333333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.main-tip {
    font-size: 12px;
    color: #999999;
    padding-left: 10px;
    border-left: 1px solid #CFCFCF;
}
.iconruxiaofuwu_danchuangguanbi {
    font-size: 12px;
}
.down-modal {
    color: #999;
    line-height: 20px;
    margin: 20px 0 20px 42px;
}
.down-modal-a {
    // color: $primary-color;
    text-decoration: underline;
}
</style>